<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>VUE第二天 数据变异</title>
</head>
<body>
  <div id="app"> 
    <p>1.数组变异</p>
    <span v-for="item in  arr1">{{item}}</span><br>
    <button @click="change1">修改数据</button>
    <p v-for="item in arr2">{{item.name}}</p>
    <button @click="change2">修改数据</button><br>
    <button @click="change22">修改数组第一项的name</button><br>
    <hr>
    <span v-for="item in arr3">{{item}}</span><br>
    <button @click="change3">修改数据</button>
    <hr>
    <p>2.对象变异</p>
    <p v-for="item in obj1">{{item}}</p>
    <button @click="changeObj1">修改对象属性</button>
    <button @click="changeObj2">新增对象属性</button>
    <button @click="changeObj3">删除对象属性</button>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        arr1: [1,2,3,4,5],
        arr2: [
          {
            name: 'iphone',
            price: 9999
          },
          {
            name: 'mi 10',
            price: 5999
          }
        ],
        arr3: [1,2,3,4,5],
        obj1: {
          name: 'Jack',
          age: 18
        }
      },
      methods: {
        // 修改数组的第一种方式：通过下标修改一整项
        change1() {
          this.arr1[2] = 3.5
        },
        change2() {
          // this.arr2[0] = {
          //   name: 'huawei',
          //   price: 8999
          // }
          // 1.通过splice()
          // this.arr2.splice(0, 1, {name: 'huawei', price: 8999})
          // 2.通过vue的$set/Vue.set(被修改的数组, index, newValue)
          vm.$set(this.arr2, 0, {name: 'huawei', price: 8999})
        },
        // 修改数组的第二种情况：直接修改长度
        change3() {
          // 错误的方式：this.arr3.length = 2;
          this.arr3.splice(2)
        },
        // 修改对象属性-正常
        changeObj1() {
          this.obj1.name = 'Ben';
        },
        // 新增对象属性
        changeObj2() {
          // 错误的方式：this.obj1.sex = '男'
          vm.$set(this.obj1, 'sex', '男');
        },
        // 删除对象属性
        changeObj3() {
          vm.$delete(this.obj1, 'name');
        },
        change22() {
          this.arr2[0].name = 'huawei p40'
        }
      },
    })
  </script>
</body>
</html>